﻿Shader "Lit/Diffuse With Shadows"
{
	Properties
	{
		[NoScaleOffset] _MainTex("Texture", 2D) = "white" {}
	}
		SubShader
	{
		Pass
		{
	Tags {"LightMode" = "ForwardBase"}
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			#include "UnityCG.cginc"
			#include "Lighting.cginc"

		// 将着色器编译成多个有阴影和没有阴影的变体
		//（我们还不关心任何光照贴图，所以跳过这些变体）
		#pragma multi_compile_fwdbase nolightmap nodirlightmap nodynlightmap novertexlight
		// 阴影 helper 函数和宏
		#include "AutoLight.cginc"

		struct v2f
		{
			float2 uv : TEXCOORD0;
			SHADOW_COORDS(1) // 将阴影数据放入 TEXCOORD1
			fixed3 diff : COLOR0;
			fixed3 ambient : COLOR1;
			float4 pos : SV_POSITION;
		};
		v2f vert(appdata_base v)
		{
			v2f o;
			o.pos = UnityObjectToClipPos(v.vertex);
			o.uv = v.texcoord;
			half3 worldNormal = UnityObjectToWorldNormal(v.normal);
			half nl = max(0, dot(worldNormal, _WorldSpaceLightPos0.xyz));
			o.diff = nl * _LightColor0.rgb;
			o.ambient = ShadeSH9(half4(worldNormal,1));
			// 计算阴影数据
			TRANSFER_SHADOW(o)
			return o;
		}

		sampler2D _MainTex;

		fixed4 frag(v2f i) : SV_Target
		{
			fixed4 col = tex2D(_MainTex, i.uv);
		// 计算阴影衰减（1.0 = 完全照亮，0.0 = 完全阴影）
		fixed shadow = SHADOW_ATTENUATION(i);
		// 用阴影使光照变暗，保持环境不变
		fixed3 lighting = i.diff * shadow + i.ambient;
		col.rgb *= lighting;
		return col;
	}
	ENDCG
}

// 阴影投射支持
UsePass "Legacy Shaders/VertexLit/SHADOWCASTER"
	}
}